package com.xinzhi.savingpot.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class NoteUtil {
    /**
     * 发送验证码
     * @param phone  手机号
     * @param VCode  验证码
     * @return   map集合  code状态码 0000 成功 msg 返回信息
     */
    public static Map<String,String> send(String phone,String VCode){
        String host = "https://intlsms.market.alicloudapi.com";
        String path = "/comms/sms/sendmsgall";
        String method = "POST";
        String appcode = "01fa85f264fc4c04bece311fa05de17d";
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        formbuilder.add("channel","0");
        formbuilder.add("callbackUrl", "http://test.dev.esandcloud.com");
        formbuilder.add("mobile", "+86"+phone);
        formbuilder.add("templateID", "20210112211410");
        formbuilder.add("templateParamSet", VCode);
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(host+path)
                .addHeader("Authorization", "APPCODE " + appcode)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .post(body)
                .build();
        Map<String,String> map = new HashMap<>();
        try {
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            map.put("code",jsonObject.getString("code"));
            map.put("msg",jsonObject.getString("msg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 生成六位数验证码
     * @return  验证码
     */
    public static String VCode(){
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {

            int r = random.nextInt(10); //每次随机出一个数字（0-9）

            code = code + r;  //把每次随机出的数字拼在一起

        }
        return code;
    }

    public static void main(String[] args) {
        System.out.println(send("15135839784",VCode()));
    }
}